package com.httpdemo.http_teaching_server.controller;

import com.httpdemo.http_teaching_server.model.User;
import com.httpdemo.http_teaching_server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UserLoginController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");

        User user = userRepository.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            return ResponseEntity.status(401).build();
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, "session=" + user.getId() + "; Path=/; HttpOnly")
                .build();
    }
}